<?php 
class Wechat_Controller extends Wy_Controller{
	function __construct(){
		parent::__construct();
		$user_agent = $_SERVER['HTTP_USER_AGENT'];
		//判断用户是否存在
		$falg = 0;
		global $falg ;
		 if (strpos($user_agent, 'MicroMessenger')) {
			$resInfoUser = $this->model('wechart')->fetch_one('weixin_config','id=1',"*");
			$config = $this->model('config')->get_config();
		//    var_dump($config);die;
			//通过code获得openid
			$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
			$nowurl = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
			if(!isset($_SESSION['openid'])){
				if (!isset($_GET['code'])) {
					//触发微信返回code码
					$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$resInfoUser["wx_appid"].'&redirect_uri='.$nowurl.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
					Header("Location: $url");
					exit;
				} else {
					//获取code码，以获取openid
					$code = $_GET['code'];
					$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $resInfoUser["wx_appid"] . '&secret=' . $resInfoUser["wx_appsecret"] . '&code=' . $code . '&grant_type=authorization_code';
					$wx = new wechat_class();
					$return = json_decode($wx->httpGet($url), true);
					$openid =$return['openid'];
					$_SESSION['openid'] = $openid;
					//判断微信openid 是否绑定用户
					if($userid = $this->model('wechart')->fetch_one('users', "openid='".$openid."'",'*')){
						$_SESSION['user_id'] = $userid['id'];
						$userInfo = $this->model('users')->get_userinfo_by_userid($userid['id']);
						$userInfo['is_apply_settlement'] = $userid['is_apply_settlement'];
						$_SESSION['user'] = $userInfo;
						if (!isset($_SESSION['login_user_safe_key'])) {
							$_SESSION['login_user_safe_key'] = false;
						} else {
							if (isset($userInfo['is_safe']) && $userInfo['is_safe'] != 1) $_SESSION['login_user_safe_key'] = true;
						}
						$falg = 1;
					}
				}
			}else{
				//判断微信openid 是否绑定用户
				if($userid = $this->model('wechart')->fetch_one('users', "openid='".$_SESSION['openid']."'",'*')){
					$_SESSION['user_id'] = $userid['id'];
					$userInfo =$this->model('users')->get_userinfo_by_userid($userid['id']);
					$userInfo['is_apply_settlement'] = $userid['is_apply_settlement'];
					$_SESSION['user'] = $userInfo;
					if (!isset($_SESSION['login_user_safe_key'])) {
						$_SESSION['login_user_safe_key'] = false;
					} else {
						if (isset($userInfo['is_safe']) && $userInfo['is_safe'] != 1) $_SESSION['login_user_safe_key'] = true;
					}
					$falg = 1;
				}
			}
		}else{
			Redirect('','请在微信里打开！');
		}
	}
}
?>